package com.xiaoxu.intranetweb.mybatisplusSzappdb.business.auth;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.Dic.UserDic;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.business.log.SysLogBu;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.dao.UserInfoDao;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.entity.*;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.excelEntity.PersonalExcelEn;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.mapper.SysUserMapper;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.service.*;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.vo.UserVo;
import com.xiaoxu.intranetweb.util.MD5Util;
import com.xiaoxu.intranetweb.util.StringUtils;
import com.xiaoxu.intranetweb.util.SzResult;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;


import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.Future;
import java.util.stream.Collectors;

import static net.sf.jsqlparser.util.validation.metadata.NamedObject.user;


@Component
@Slf4j
public class UserBu {
    @Autowired
    private ISysUserService iSysUserService;
    @Autowired
    private UserInfoDao userInfoDao;
    @Autowired
    private ISysDicService iSysDicService;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private ICCompanysService iCCompanysService;
    @Autowired
    private ISysUserOrgConnService iSysUserOrgConnService;
    @Autowired
    private ISysUserRoleConnService iSysUserRoleConnService;
    @Autowired
    private ISysUserWxConnService iSysUserWxConnService;
    @Autowired
    private ISysRoleService iSysRoleService;
    @Autowired
    private ISysPartService iSysPartService;
    @Autowired
    private SysLogBu sysLogBu;
    @Autowired
    private ISysUserPartConnService iSysUserPartConnService;
    @Autowired
    private ITPlantsService iTPlantsService;
    @Autowired
    private ISysUserPlantConnService iSysUserPlantConnService;
    @Autowired
    private ISysRoleInfoFunctionWebService iSysRoleInfoFunctionWebService;
    @Autowired
    private ISysRoleInfoFunctionService iSysRoleInfoFunctionService;
    @Autowired
    private ISysRoleInfoFunctionService sysRoleInfoFunctionService;
    @Autowired
    private ISysRoleInfoFunctionWebService sysRoleInfoFunctionWebService;
    @Autowired
    private UserDic userDic;

    //    获取用户的通用轻量接口
    public SzResult getSystemUser(String value, String token, String plantId) throws Exception {
        //String plantId = plantId;
//       将角色id直接填进去
        List<String> roleId = new ArrayList<>();
        roleId.add("efa58b0230d65d55c8b87b1def147e6c");
        roleId.add("efa58b0230d65d55c8b87b1def147e9a");
        roleId.add("2eb960e63d7911ed8af2f46b8c8e2f1b");
        QueryWrapper<SysUserRoleConn> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.in("ROLE_ID", roleId);
        List<SysUserRoleConn> sysUserRoleConnList = iSysUserRoleConnService.list(queryWrapper1);
        List<String> userId = new ArrayList<>();
        for (SysUserRoleConn sysUserRoleConn : sysUserRoleConnList) {
            userId.add(sysUserRoleConn.getUserId());
        }
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        if (value != null && !value.equals("")) {
//    查用户名或者真实姓名或者电话,使用箭头函数
            queryWrapper.and(i -> i.like("USER_NAME", value).or().like("TRUE_NAME", value).or().like("PHONE", value));
        }
        queryWrapper.in("ID", userId);
        queryWrapper.eq("DATA_FROM", plantId);
        queryWrapper.eq("DEL_FLAG", 0);
        queryWrapper.select(SysUser.class, info -> !info.getColumn().equals("password") && !info.getColumn().equals("pwd_detail"));
        queryWrapper.orderByDesc("USER_CREAT_TIME");
        List<SysUser> sysUserList = iSysUserService.list(queryWrapper);
        return SzResult.success(sysUserList);
    }

    //    新增用户
//    事务
    @Transactional
    public SzResult addUser(String token, UserVo userVo, String plantId) throws Exception {
        SysUser user = userInfoDao.getUser(StpUtil.getLoginIdByToken(token).toString());
        // String plantId = plantId;
        QueryWrapper<SysUser> queryWrapper6 = new QueryWrapper<>();
        queryWrapper6.eq("PHONE", userVo.getPhone());
        queryWrapper6.eq("DEL_FLAG", 0);
        SysUser sysUser1 = iSysUserService.getOne(queryWrapper6);
        if (sysUser1 != null) {
            return SzResult.error("该手机号已存在");
        }
        SysUser sysUser = new SysUser();
        String uuid = java.util.UUID.randomUUID().toString().replace("-", "");
        sysUser.setId(uuid);
        sysUser.setPhone(userVo.getPhone());
        sysUser.setEnableFlag(1);
        sysUser.setDelFlag(0);
        sysUser.setTrueName(userVo.getTrueName());
        sysUser.setIdCard(userVo.getIdCard());
        sysUser.setEmail(userVo.getEmail());
        sysUser.setIfWeb(userVo.getIfWeb());
        sysUser.setIfApp(userVo.getIfApp());
        sysUser.setDataFrom(plantId);
        sysUser.setUserCreatTime(LocalDateTime.now());
        sysUser.setUserCreatorId(user.getId());
        QueryWrapper<SysPart> queryWrapper10 = new QueryWrapper<>();
        queryWrapper10.eq("ID", userVo.getPartId());
        SysPart sysPart1 = iSysPartService.getOne(queryWrapper10);
        String partRole = sysPart1.getPartRole();
        QueryWrapper<SysRole> queryWrapper11 = new QueryWrapper<>();
        queryWrapper11.eq("ID", partRole);
        SysRole sysRole3 = iSysRoleService.getOne(queryWrapper11);
        QueryWrapper<SysDic> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("DIC_TYPE", "userPrefix");
        queryWrapper.eq("DIC_KEY", sysRole3.getRoleCode().substring(0, 1));
        SysDic sysDic = iSysDicService.getOne(queryWrapper);
        int prefixLength = sysDic.getDicVal().length();
        String lastName = sysUserMapper.getLatestUserName(sysDic.getDicVal());
//        System.out.println("sysDic.getDicVal():"+sysDic.getDicVal());
//        System.out.println("lastName:"+lastName);//lastName:yh_dw362
//        lastName是用户名称，在sysDic.getDicVal()后面是数字，自动加1
        if (lastName != null) {
//            String lastNum = lastName.substring(sysDic.getDicVal().length());
//            找到sysDic.getDicVal()的值将这个的值加上前面的数据全部不要
            String lastNum = lastName.substring(lastName.indexOf(sysDic.getDicVal()) + sysDic.getDicVal().length());
            int num = Integer.parseInt(lastNum);
            num++;
            sysUser.setUserName(sysDic.getDicVal() + num);
        } else {
            sysUser.setUserName(sysDic.getDicVal() + "1");
        }
        QueryWrapper<SysDic> queryWrapper5 = new QueryWrapper<>();
        queryWrapper5.eq("DIC_TYPE", "userIniPwd");
        queryWrapper5.eq("DIC_KEY", sysRole3.getRoleCode().substring(0, 1));
        SysDic sysDic1 = iSysDicService.getOne(queryWrapper5);
        sysUser.setPwdDetail(sysDic1.getDicVal());
        sysUser.setPassword(MD5Util.getMd5(sysDic1.getDicVal()).toUpperCase());
        iSysUserService.save(sysUser);
//        save之后，sysUser就有了id
//            关联单位
        QueryWrapper<CCompanys> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("ID", userVo.getCoId());
        CCompanys cCompanys = iCCompanysService.getOne(queryWrapper1);
        SysUserOrgConn sysUserOrgConn = new SysUserOrgConn();
        sysUserOrgConn.setUserId(sysUser.getId());
        sysUserOrgConn.setOrgId(cCompanys.getId());
        iSysUserOrgConnService.save(sysUserOrgConn);
//            关联角色
        SysUserRoleConn sysUserRoleConn = new SysUserRoleConn();
        sysUserRoleConn.setUserId(sysUser.getId());
        sysUserRoleConn.setRoleId(sysRole3.getId());
        iSysUserRoleConnService.save(sysUserRoleConn);
//            关联电厂，这个表里只有一个电厂，所以直接写死
        QueryWrapper<TPlants> queryWrapper4 = new QueryWrapper<>();
        queryWrapper4.eq("ID", plantId);
        TPlants tPlants = iTPlantsService.getOne(queryWrapper4);
        SysUserPlantConn sysUserPlantConn = new SysUserPlantConn();
        sysUserPlantConn.setUserId(sysUser.getId());
        sysUserPlantConn.setPlantId(tPlants.getId());
        iSysUserPlantConnService.save(sysUserPlantConn);
//            关联部门
        QueryWrapper<SysPart> queryWrapper3 = new QueryWrapper<>();
        queryWrapper3.eq("ID", userVo.getPartId());
        SysPart sysPart = iSysPartService.getOne(queryWrapper3);
        SysUserPartConn sysUserPartConn1 = new SysUserPartConn();
        sysUserPartConn1.setUserId(sysUser.getId());
        sysUserPartConn1.setPartId(sysPart.getId());
        iSysUserPartConnService.save(sysUserPartConn1);
//            然后反过来将绑定的部门里默认权限交给这个新用户
        UpdateWrapper<SysUser> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("ID", uuid);
        updateWrapper.set("APP_AUTHORITY1", sysPart.getDefaultCodeApp());
        updateWrapper.set("APP_AUTHORITY2", sysPart.getDefaultCodeWeb());
        iSysUserService.update(updateWrapper);
        sysLogBu.logRecord("新增用户", user.getTrueName(), "新增了" + sysRole3.getRoleName() + "用户【" + sysUser.getTrueName() + "】", plantId);
//        拿到用户信息
        Map<String, Object> map = new HashMap<>();
        map.put("userName", sysUser.getUserName());
        map.put("password", sysUser.getPwdDetail());
        return SzResult.success(map);
    }

    //    修改用户
    @Transactional
    public SzResult updateUser(String token, UserVo userVo, List<String> plantList, String plantId) throws Exception {
        // 获取当前登录用户信息
        SysUser user = userInfoDao.getUser(StpUtil.getLoginIdByToken(token).toString());
        // 根据id查询要修改的用户信息
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", userVo.getId());
        SysUser sysUser = iSysUserService.getOne(queryWrapper);
        // 记录修改信息
        StringBuilder logMsg = new StringBuilder();
        if (!userVo.getPhone().equals(sysUser.getPhone())) {
            logMsg.append("将手机号由").append(sysUser.getPhone()).append("修改为").append(userVo.getPhone()).append("，");
            sysUser.setPhone(userVo.getPhone());
        }
        if (!userVo.getTrueName().equals(sysUser.getTrueName())) {
            logMsg.append("将真实姓名由").append(sysUser.getTrueName()).append("修改为").append(userVo.getTrueName()).append("，");
            sysUser.setTrueName(userVo.getTrueName());
        }
//        if (!userVo.getIdCard().equals(sysUser.getIdCard())) {
//            logMsg.append("将身份证号由").append(sysUser.getIdCard()).append("修改为").append(userVo.getIdCard()).append("，");
//            sysUser.setIdCard(userVo.getIdCard());
//        }
//        if (!userVo.getEmail().equals(sysUser.getEmail())) {
//            logMsg.append("将邮箱由").append(sysUser.getEmail()).append("修改为").append(userVo.getEmail()).append("，");
//            sysUser.setEmail(userVo.getEmail());
//        }
        if (sysUser.getIfWeb() != null) {
            if (!userVo.getIfWeb().equals(sysUser.getIfWeb())) {
//        如果是1，就是要修改为是web登录，如果是0，就是要修改为不是web登录
                if (userVo.getIfWeb() == 1) {
                    logMsg.append("将是否Web登录由").append("【不是】").append("修改为").append("【是】").append("，");
                } else {
                    logMsg.append("将是否Web登录由").append("【不是】").append("修改为").append("【是】").append("，");
                }
                if (userVo.getIfWeb() == 0) {
                    logMsg.append("将是否Web登录由").append("【是】").append("修改为").append("【不是】").append("，");
                } else {
                    logMsg.append("将是否Web登录由").append("【是】").append("修改为").append("【不是】").append("，");
                }
                sysUser.setIfWeb(userVo.getIfWeb());
            }
        } else {
            if (userVo.getIfWeb() == 1) {
                logMsg.append("将是否Web登录由").append("【不是】").append("修改为").append("【是】").append("，");
            } else {
                logMsg.append("将是否Web登录由").append("【不是】").append("修改为").append("【是】").append("，");
            }
            if (userVo.getIfWeb() == 0) {
                logMsg.append("将是否Web登录由").append("【是】").append("修改为").append("【不是】").append("，");
            } else {
                logMsg.append("将是否Web登录由").append("【是】").append("修改为").append("【不是】").append("，");
            }
            sysUser.setIfWeb(userVo.getIfWeb());
        }
        if (sysUser.getIfApp() != null) {

            if (!userVo.getIfApp().equals(sysUser.getIfApp())) {
//        如果是1，就是要修改为是app登录，如果是0，就是要修改为不是app登录
                if (userVo.getIfApp() == 1) {
                    logMsg.append("将是否App登录由").append("【不是】").append("修改为").append("【是】").append("，");
                } else {
                    logMsg.append("将是否App登录由").append("【是】").append("修改为").append("【不是】").append("，");
                }
                if (userVo.getIfApp() == 0) {
                    logMsg.append("将是否App登录由").append("【是】").append("修改为").append("【不是】").append("，");
                } else {
                    logMsg.append("将是否App登录由").append("【是】").append("修改为").append("【不是】").append("，");
                }
                sysUser.setIfApp(userVo.getIfApp());
            }

        } else {
            if (userVo.getIfApp() == 1) {
                logMsg.append("将是否App登录由").append("【不是】").append("修改为").append("【是】").append("，");
            } else {
                logMsg.append("将是否App登录由").append("【是】").append("修改为").append("【不是】").append("，");
            }
            if (userVo.getIfApp() == 0) {
                logMsg.append("将是否App登录由").append("【是】").append("修改为").append("【不是】").append("，");
            } else {
                logMsg.append("将是否App登录由").append("【是】").append("修改为").append("【不是】").append("，");
            }
            sysUser.setIfApp(userVo.getIfApp());
        }
        sysUser.setUserUpdateTime(LocalDateTime.now());
        sysUser.setUserUpdatorId(user.getId());

        // 关联单位
        QueryWrapper<CCompanys> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("ID", userVo.getCoId());
        CCompanys cCompanys = iCCompanysService.getOne(queryWrapper1);
        QueryWrapper<SysUserOrgConn> queryWrapper4 = new QueryWrapper<>();
        queryWrapper4.eq("USER_ID", userVo.getId());
        SysUserOrgConn sysUserOrgConn1 = iSysUserOrgConnService.getOne(queryWrapper4);
//    再查一下，如果没有关联，就新增，如果有关联，就修改
        if (sysUserOrgConn1 == null) {
            SysUserOrgConn sysUserOrgConn = new SysUserOrgConn();
            sysUserOrgConn.setUserId(userVo.getId());
            sysUserOrgConn.setOrgId(cCompanys.getId());
            iSysUserOrgConnService.save(sysUserOrgConn);
            QueryWrapper<CCompanys> queryWrapper2 = new QueryWrapper<>();
            queryWrapper2.eq("ID", userVo.getCoId());
            CCompanys cCompanys1 = iCCompanysService.getOne(queryWrapper2);
            logMsg.append("将单位由").append("【无】").append("修改为").append("【").append(cCompanys1.getCpyCo()).append("】").append("，");
        } else {
//        先查是否相等，如果相等，就不修改
            if (!sysUserOrgConn1.getOrgId().equals(cCompanys.getId())) {
                sysUserOrgConn1.setOrgId(cCompanys.getId());
                iSysUserOrgConnService.updateById(sysUserOrgConn1);
                QueryWrapper<CCompanys> queryWrapper2 = new QueryWrapper<>();
                queryWrapper2.eq("ID", userVo.getCoId());
                CCompanys cCompanys1 = iCCompanysService.getOne(queryWrapper2);
                QueryWrapper<CCompanys> queryWrapper3 = new QueryWrapper<>();
                queryWrapper3.eq("ID", sysUserOrgConn1.getOrgId());
                CCompanys cCompanys2 = iCCompanysService.getOne(queryWrapper3);
                logMsg.append("将单位由").append("【").append(cCompanys2.getCpyCo()).append("】").append("修改为").append("【").append(cCompanys1.getCpyCo()).append("】").append("，");
            }

        }
        // 关联角色
        QueryWrapper<SysRole> queryWrapper3 = new QueryWrapper<>();

        queryWrapper3.eq("ID", userVo.getRoleId());
        SysRole sysRole = iSysRoleService.getOne(queryWrapper3);
        QueryWrapper<SysUserRoleConn> queryWrapper7 = new QueryWrapper<>();
        queryWrapper7.eq("USER_ID", userVo.getId());
        SysUserRoleConn sysUserRoleConn = iSysUserRoleConnService.getOne(queryWrapper7);
//   再查一下，如果没有关联，就新增，如果有关联，就修改
        if (sysUserRoleConn == null) {
            SysUserRoleConn sysUserRoleConn1 = new SysUserRoleConn();
            sysUserRoleConn1.setUserId(userVo.getId());
            sysUserRoleConn1.setRoleId(sysRole.getId());
            iSysUserRoleConnService.save(sysUserRoleConn1);
            QueryWrapper<SysRole> queryWrapper8 = new QueryWrapper<>();
            queryWrapper8.eq("ID", userVo.getRoleId());
            SysRole sysRole1 = iSysRoleService.getOne(queryWrapper8);

            logMsg.append("将角色由").append("【无】").append("修改为").append("【").append(sysRole1.getRoleName()).append("】").append("，");
        } else {
//        先查是否相等，如果相等，就不修改
            if (!sysUserRoleConn.getRoleId().equals(sysRole.getId())) {
                sysUserRoleConn.setRoleId(sysRole.getId());
                iSysUserRoleConnService.updateById(sysUserRoleConn);
                QueryWrapper<SysRole> queryWrapper8 = new QueryWrapper<>();
                queryWrapper8.eq("ID", userVo.getRoleId());
                SysRole sysRole1 = iSysRoleService.getOne(queryWrapper8);
                QueryWrapper<SysRole> queryWrapper9 = new QueryWrapper<>();
                queryWrapper9.eq("ID", sysUserRoleConn.getRoleId());
                SysRole sysRole2 = iSysRoleService.getOne(queryWrapper9);
                logMsg.append("将角色由").append("【").append(sysRole2.getRoleName()).append("】").append("修改为").append("【").append(sysRole1.getRoleName()).append("】").append("，");
            }
        }
        // 关联部门
        QueryWrapper<SysPart> queryWrapper5 = new QueryWrapper<>();
        queryWrapper5.eq("ID", userVo.getPartId());
        SysPart sysPart = iSysPartService.getOne(queryWrapper5);
        QueryWrapper<SysUserPartConn> queryWrapper10 = new QueryWrapper<>();
        queryWrapper10.eq("USER_ID", userVo.getId());
        SysUserPartConn sysUserPartConn = iSysUserPartConnService.getOne(queryWrapper10);
//   再查一下，如果没有关联，就新增，如果有关联，就修改
        if (sysUserPartConn == null) {
            SysUserPartConn sysUserPartConn1 = new SysUserPartConn();
            sysUserPartConn1.setUserId(userVo.getId());
            sysUserPartConn1.setPartId(sysPart.getId());
            iSysUserPartConnService.save(sysUserPartConn1);
            QueryWrapper<SysPart> queryWrapper11 = new QueryWrapper<>();
            queryWrapper11.eq("ID", userVo.getPartId());
            SysPart sysPart1 = iSysPartService.getOne(queryWrapper11);
            //            修改用户角色后直接赋值新的角色权限，覆盖掉原先的角色权限
            if (sysPart1.getDefaultCodeApp()!=null) {
                sysUser.setAppAuthority1(sysPart1.getDefaultCodeApp());
            }
            if (sysPart1.getDefaultCodeWeb()!=null) {
                sysUser.setAppAuthority1(sysPart1.getDefaultCodeWeb());
            }
            logMsg.append("将角色由").append("【无】").append("修改为").append("【").append(sysPart1.getPartName()).append("】").append("，");
        } else {
//        先查是否相等，如果相等，就不修改
            if (!sysUserPartConn.getPartId().equals(sysPart.getId())) {
                sysUserPartConn.setPartId(sysPart.getId());
                iSysUserPartConnService.updateById(sysUserPartConn);
                QueryWrapper<SysPart> queryWrapper11 = new QueryWrapper<>();
                queryWrapper11.eq("ID", userVo.getPartId());
                SysPart sysPart1 = iSysPartService.getOne(queryWrapper11);
                QueryWrapper<SysPart> queryWrapper12 = new QueryWrapper<>();
                queryWrapper12.eq("ID", sysUserPartConn.getPartId());
                SysPart sysPart2 = iSysPartService.getOne(queryWrapper12);
                logMsg.append("将部门由").append("【").append(sysPart2.getPartName()).append("】").append("修改为").append("【").append(sysPart1.getPartName()).append("】").append("，");
            }
        }
        //关联厂
        if (plantList != null && !plantList.isEmpty()) {
            for (String s : plantList) {
                QueryWrapper<TPlants> queryWrapper12 = new QueryWrapper<>();
                queryWrapper12.eq("ID", s);
                TPlants tPlants = iTPlantsService.getOne(queryWrapper12);
                QueryWrapper<SysUserPlantConn> queryWrapper13 = new QueryWrapper<>();
                queryWrapper13.eq("USER_ID", userVo.getId());
                queryWrapper13.eq("PLANT_ID", tPlants.getId());
                SysUserPlantConn sysUserPlantConn = iSysUserPlantConnService.getOne(queryWrapper13);
//   再查一下，如果没有关联，就新增，如果有关联，就修改
                if (sysUserPlantConn == null) {
                    SysUserPlantConn sysUserPlantConn1 = new SysUserPlantConn();
                    sysUserPlantConn1.setUserId(userVo.getId());
                    sysUserPlantConn1.setPlantId(tPlants.getId());
                    iSysUserPlantConnService.save(sysUserPlantConn1);
                    QueryWrapper<TPlants> queryWrapper14 = new QueryWrapper<>();
                    queryWrapper14.eq("ID", s);
                    TPlants tPlants1 = iTPlantsService.getOne(queryWrapper14);
                    logMsg.append("将电厂由").append("【无】").append("修改为").append("【").append(tPlants1.getPlantFullName()).append("】").append("，");
                } else {
//        先查是否相等，如果不相等，就新增
                    if (!sysUserPlantConn.getPlantId().equals(tPlants.getId())) {
                        //新增
                        SysUserPlantConn sysUserPlantConn2 = new SysUserPlantConn();
                        sysUserPlantConn2.setUserId(userVo.getId());
                        sysUserPlantConn2.setPlantId(tPlants.getId());
                        iSysUserPlantConnService.save(sysUserPlantConn2);
                        QueryWrapper<TPlants> queryWrapper14 = new QueryWrapper<>();
                        queryWrapper14.eq("ID", s);
                        TPlants tPlants1 = iTPlantsService.getOne(queryWrapper14);
                        logMsg.append("将电厂由").append("【无】").append("修改为").append("【").append(tPlants1.getPlantFullName()).append("】").append("，");
                    }
                }
            }
        }
        // 记录日志
        if (logMsg.length() > 0) {
            String logContent = logMsg.substring(0, logMsg.length() - 1);
            sysLogBu.logRecord("修改用户", user.getTrueName(), "修改用户【" + sysUser.getTrueName() + "】的信息" + logContent, plantId);
        }
        iSysUserService.updateById(sysUser);
        return SzResult.Success();
    }

    //    删除用户
    public SzResult deleteUser(String token, String id, String plantId) throws Exception {
        SysUser user = userInfoDao.getUser(StpUtil.getLoginIdByToken(token).toString());
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ID", id);
        SysUser sysUser = iSysUserService.getOne(queryWrapper);
        sysUser.setDelFlag(1);
        sysUser.setEnableFlag(0);
        iSysUserService.updateById(sysUser);
//        iSysUserService.removeById(id);
//        QueryWrapper<SysUserOrgConn> queryWrapper1 = new QueryWrapper<>();
//        queryWrapper1.eq("USER_ID", id);
//        iSysUserOrgConnService.remove(queryWrapper1);
//        QueryWrapper<SysUserRoleConn> queryWrapper2 = new QueryWrapper<>();
//        queryWrapper2.eq("USER_ID", id);
//        iSysUserRoleConnService.remove(queryWrapper2);
//        QueryWrapper<SysUserPartConn> queryWrapper3 = new QueryWrapper<>();
//        queryWrapper3.eq("USER_ID", id);
//        iSysUserPartConnService.remove(queryWrapper3);
        sysLogBu.logRecord("删除用户", user.getTrueName(), "删除了用户【" + sysUser.getTrueName() + "】", plantId);
        return SzResult.Success();
    }

    //    拿到所有用户
    public SzResult  getAllUser(String page, String pageSize, String userName, String phone,String coId, String roleId, String plantId) throws Exception {
        //String plantId = plantId;
        List<SysUser> sysUsers = new ArrayList<>();
        //如果不传page和pageSize则默认查询所有
        if (page == null || page.equals("") || pageSize == null || pageSize.equals("")) {
            List<String> userIds = null;
            if (roleId != null && !roleId.equals("")) {
                QueryWrapper<SysUserRoleConn> queryWrapper1 = new QueryWrapper<>();
                queryWrapper1.eq("ROLE_ID", roleId);
                List<SysUserRoleConn> sysUserRoleConns = iSysUserRoleConnService.list(queryWrapper1);
                userIds = sysUserRoleConns.stream()
                        .map(SysUserRoleConn::getUserId)
                        .collect(Collectors.toList());
            }
            // 使用这些用户ID作为基础，添加其他锁定条件
            QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
            queryWrapper.in(userIds != null, "ID", userIds);

            if (userName != null && !userName.equals("")) {
                queryWrapper.and(i -> i.like("USER_NAME", userName).or().like("TRUE_NAME", userName));
            }

            if (phone != null && !phone.equals("")) {
                queryWrapper.like("PHONE", phone);
            }
            if (StringUtils.isNotEmpty(coId)){
                QueryWrapper<SysUserOrgConn> userOrgConnQueryWrapper = new QueryWrapper<>();
                userOrgConnQueryWrapper.eq("ORG_id",coId);
                List<String> list = iSysUserOrgConnService.list(userOrgConnQueryWrapper).stream().map((item)->{
                    return item.getUserId();
                }).collect(Collectors.toList());
                if (list.size() !=0) {
                    queryWrapper.in("ID", list);
                }
            }

//            queryWrapper.eq("DATA_FROM", plantId);
            queryWrapper.ne("DEL_FLAG", 1);
            queryWrapper.orderByDesc("USER_CREAT_TIME");
            sysUsers = iSysUserService.list(queryWrapper);
            int total = sysUsers.size();
            List<UserVo> userVos = new ArrayList<>();
            for (SysUser sysUser : sysUsers) {
                UserVo userVo = new UserVo();
                userVo.setId(sysUser.getId());
                userVo.setTrueName(sysUser.getTrueName());
                userVo.setUserName(sysUser.getUserName());
                userVo.setPhone(sysUser.getPhone());
                userVo.setEmail(sysUser.getEmail());
                userVo.setIfApp(sysUser.getIfApp());
                userVo.setIfWeb(sysUser.getIfWeb());
                userVo.setIdCard(sysUser.getIdCard());
                userVo.setCreateTime(sysUser.getUserCreatTime());
                userVo.setUpdateTime(sysUser.getUserUpdateTime());
                QueryWrapper<SysUserWxConn> wxConnQueryWrapper = new QueryWrapper<>();
                wxConnQueryWrapper.eq("USER_ID",sysUser.getId());
                SysUserWxConn wxConn = iSysUserWxConnService.getOne(wxConnQueryWrapper);
                if (wxConn != null) {
                    userVo.setWxOpenId(wxConn.getWxOpenId());
                }
                QueryWrapper<SysUserOrgConn> queryWrapper4 = new QueryWrapper<>();
                queryWrapper4.eq("USER_ID", sysUser.getId());
                SysUserOrgConn sysUserOrgConn = iSysUserOrgConnService.getOne(queryWrapper4);
                if (sysUserOrgConn != null) {
                    QueryWrapper<CCompanys> queryWrapper1 = new QueryWrapper<>();
                    queryWrapper1.eq("ID", sysUserOrgConn.getOrgId());
                    queryWrapper1.eq("DATA_FROM", plantId);
                    CCompanys cCompanys = iCCompanysService.getOne(queryWrapper1);
                    userVo.setCoId(cCompanys.getId());
                    userVo.setOrgName(cCompanys.getCpyCo() + "." + cCompanys.getCpyChico());
                } else {
                    userVo.setOrgName("无");
                }
                QueryWrapper<SysUserRoleConn> queryWrapper1 = new QueryWrapper<>();
                queryWrapper1.eq("USER_ID", sysUser.getId());
                SysUserRoleConn sysUserRoleConn = iSysUserRoleConnService.getOne(queryWrapper1);
                if (sysUserRoleConn != null) {
                    QueryWrapper<SysRole> queryWrapper2 = new QueryWrapper<>();
                    queryWrapper2.eq("ID", sysUserRoleConn.getRoleId());
                    SysRole sysRole = iSysRoleService.getOne(queryWrapper2);
                    userVo.setRoleId(sysRole.getId());
                    userVo.setRoleName(sysRole.getRoleName());
                    userVo.setRoleLevel(sysRole.getRoleCode().substring(0, 1));
                } else {
                    userVo.setRoleName("无");
                }
                QueryWrapper<SysUserPartConn> queryWrapper2 = new QueryWrapper<>();
                queryWrapper2.eq("USER_ID", sysUser.getId());
                SysUserPartConn sysUserPartConn = iSysUserPartConnService.getOne(queryWrapper2);
                if (sysUserPartConn != null) {
                    QueryWrapper<SysPart> queryWrapper3 = new QueryWrapper<>();
                    queryWrapper3.eq("ID", sysUserPartConn.getPartId());
                    queryWrapper3.eq("DATA_FROM", plantId);
                    SysPart sysPart = iSysPartService.getOne(queryWrapper3);
                    userVo.setPartName(sysPart.getPartName());
                    userVo.setPartId(sysPart.getId());
                } else {
                    userVo.setPartName("无");
                }
                if (sysUser.getUserCreatorId() != null && !sysUser.getUserCreatorId().equals("")) {
                    QueryWrapper<SysUser> queryWrapper6 = new QueryWrapper<>();
                    queryWrapper6.eq("ID", sysUser.getUserCreatorId());
                    queryWrapper6.eq("DATA_FROM", plantId);
                    SysUser sysUser1 = iSysUserService.getOne(queryWrapper6);
                    userVo.setCreateBy(sysUser1.getTrueName());
                }
                if (sysUser.getUserUpdatorId() != null && !sysUser.getUserUpdatorId().equals("")) {
                    QueryWrapper<SysUser> queryWrapper7 = new QueryWrapper<>();
                    queryWrapper7.eq("ID", sysUser.getUserUpdatorId());
                    SysUser sysUser2 = iSysUserService.getOne(queryWrapper7);
                    if (sysUser2 != null)
                        userVo.setUpdateBy(sysUser2.getTrueName());
                }
                if (null != sysUser.getAppAuthority1()) {
                    String defaultCodeApp = sysUser.getAppAuthority1();
                    char[] arr = defaultCodeApp.toCharArray();
                    List<String> list1 = new ArrayList<>();
                    for (int i = 0; i < arr.length; i++) {
                        String str = String.valueOf(arr[i]);
                        if (str.equals("1")) {//i=1
                            QueryWrapper<SysRoleInfoFunction> queryWrapper3 = new QueryWrapper<>();
                            queryWrapper3.eq("WEB_FUNCTION_NUMBER", i);
                            SysRoleInfoFunction one = iSysRoleInfoFunctionService.getOne(queryWrapper3);
                            if (one == null) {
                                continue;
                            }
                            String webFunctionExplain = one.getWebFunctionExplain();
                            list1.add(webFunctionExplain);
                        }
                        userVo.setAppNameList(list1);
                    }
                }
                if (null != sysUser.getAppAuthority2()) {

                    String defaultCodeWeb = sysUser.getAppAuthority2();
                    char[] arr1 = defaultCodeWeb.toCharArray();
                    List<String> list2 = new ArrayList<>();
                    for (int i = 0; i < arr1.length; i++) {
                        String str = String.valueOf(arr1[i]);
                        if (str.equals("1")) {//i=1
                            QueryWrapper<SysRoleInfoFunction> queryWrapper3 = new QueryWrapper<>();
                            queryWrapper3.eq("WEB_FUNCTION_NUMBER", i);
                            SysRoleInfoFunction one = iSysRoleInfoFunctionService.getOne(queryWrapper3);
                            if (one == null) {
                                continue;
                            }
                            String webFunctionExplain = one.getWebFunctionExplain();
                            list2.add(webFunctionExplain);
                        }
                        userVo.setWebNameList(list2);
                    }
                }
                QueryWrapper<SysUserPlantConn> queryWrapper8 = new QueryWrapper<>();
                queryWrapper8.eq("USER_ID", sysUser.getId());
                List<String> list = new ArrayList<>();
                List<String> list1 = new ArrayList<>();
                List<SysUserPlantConn> userPlantConnList = iSysUserPlantConnService.list(queryWrapper8);
                for (SysUserPlantConn sysUserPlantConn : userPlantConnList) {
                    QueryWrapper<TPlants> queryWrapper9 = new QueryWrapper<>();
                    queryWrapper9.eq("ID", sysUserPlantConn.getPlantId());
                    TPlants tPlants = iTPlantsService.getOne(queryWrapper9);
                    String plantFullName = tPlants.getPlantFullName();
                    list.add(plantFullName);
                    list1.add(tPlants.getId());
                }
                userVo.setConnectPlantList(list);
                userVo.setConnectPlantIdList(list1);
                userVos.add(userVo);
            }
            Map<String, Object> map = new HashMap<>();
            map.put("total", total);
            map.put("list", userVos);
            return SzResult.success(map);
        } else {
            Page<SysUser> page1 = new Page<>(Integer.parseInt(page), Integer.parseInt(pageSize));
            List<String> userIds = null;
            if (roleId != null && !roleId.equals("") ) {
                QueryWrapper<SysUserRoleConn> queryWrapper1 = new QueryWrapper<>();
                queryWrapper1.eq("ROLE_ID", roleId);
                List<SysUserRoleConn> sysUserRoleConns = iSysUserRoleConnService.list(queryWrapper1);
                userIds = sysUserRoleConns.stream()
                        .map(SysUserRoleConn::getUserId)
                        .collect(Collectors.toList());
            }
            // 使用这些用户ID作为基础，添加其他锁定条件
            QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
            queryWrapper.in(userIds != null, "ID", userIds);


            if (userName != null && !userName.equals("")) {
                queryWrapper.and(i -> i.eq("USER_NAME", userName).or().like("TRUE_NAME", userName));
            }

            if (phone != null && !phone.equals("")) {
                queryWrapper.like("PHONE", phone);
            }
            if (StringUtils.isNotEmpty(coId)){
                QueryWrapper<SysUserOrgConn> userOrgConnQueryWrapper = new QueryWrapper<>();
                userOrgConnQueryWrapper.eq("ORG_id",coId);
                List<String> list = iSysUserOrgConnService.list(userOrgConnQueryWrapper).stream().map((item)->{
                   return item.getUserId();
                }).collect(Collectors.toList());
                if (list.size() !=0) {
                    queryWrapper.in("ID", list);
                }
            }
//            queryWrapper.eq("DATA_FROM", plantId);
            queryWrapper.ne("DEL_FLAG", 1);
            queryWrapper.orderByDesc("USER_CREAT_TIME");
            IPage<SysUser> sysUserIPage = iSysUserService.page(page1, queryWrapper);
            sysUsers = sysUserIPage.getRecords();
            List<UserVo> userVos = new ArrayList<>();
            for (SysUser sysUser : sysUsers) {
                UserVo userVo = new UserVo();
                userVo.setId(sysUser.getId());
                userVo.setTrueName(sysUser.getTrueName());
                userVo.setUserName(sysUser.getUserName());
                userVo.setPhone(sysUser.getPhone());
                userVo.setEmail(sysUser.getEmail());
                userVo.setIfApp(sysUser.getIfApp());
                userVo.setIfWeb(sysUser.getIfWeb());
                userVo.setIdCard(sysUser.getIdCard());
                userVo.setCreateTime(sysUser.getUserCreatTime());
                userVo.setUpdateTime(sysUser.getUserUpdateTime());
                userVo.setEnableFlag(sysUser.getEnableFlag());
                QueryWrapper<SysUserWxConn> wxConnQueryWrapper = new QueryWrapper<>();
                wxConnQueryWrapper.eq("USER_ID",sysUser.getId());
                SysUserWxConn wxConn = iSysUserWxConnService.getOne(wxConnQueryWrapper);
                if (wxConn != null) {
                    userVo.setWxOpenId(wxConn.getWxOpenId());
                }
                QueryWrapper<SysUserOrgConn> queryWrapper4 = new QueryWrapper<>();
                queryWrapper4.eq("USER_ID", sysUser.getId());
                SysUserOrgConn sysUserOrgConn = iSysUserOrgConnService.getOne(queryWrapper4);
                if (sysUserOrgConn != null) {
                    QueryWrapper<CCompanys> queryWrapper1 = new QueryWrapper<>();
                    queryWrapper1.eq("ID", sysUserOrgConn.getOrgId());
                    CCompanys cCompanys = iCCompanysService.getOne(queryWrapper1);
                    userVo.setCoId(cCompanys.getId());
                    userVo.setOrgName(cCompanys.getCpyCo());
                } else {
                    userVo.setOrgName("无");
                }
                QueryWrapper<SysUserRoleConn> queryWrapper1 = new QueryWrapper<>();
                queryWrapper1.eq("USER_ID", sysUser.getId());
                SysUserRoleConn sysUserRoleConn = iSysUserRoleConnService.getOne(queryWrapper1);
                if (sysUserRoleConn != null) {
                    QueryWrapper<SysRole> queryWrapper2 = new QueryWrapper<>();
                    queryWrapper2.eq("ID", sysUserRoleConn.getRoleId());
                    SysRole sysRole = iSysRoleService.getOne(queryWrapper2);
                    userVo.setRoleId(sysRole.getId());
                    userVo.setRoleName(sysRole.getRoleName());
                    userVo.setRoleLevel(sysRole.getRoleCode().substring(0, 1));
                } else {
                    userVo.setRoleName("无");
                }
                QueryWrapper<SysUserPartConn> queryWrapper2 = new QueryWrapper<>();
                queryWrapper2.eq("USER_ID", sysUser.getId());
                SysUserPartConn sysUserPartConn = iSysUserPartConnService.getOne(queryWrapper2);
                if (sysUserPartConn != null) {
                    QueryWrapper<SysPart> queryWrapper3 = new QueryWrapper<>();
                    queryWrapper3.eq("ID", sysUserPartConn.getPartId());
                    SysPart sysPart = iSysPartService.getOne(queryWrapper3);
                    userVo.setPartName(sysPart.getPartName());
                    userVo.setPartId(sysPart.getId());
                } else {
                    userVo.setPartName("无");
                }
                if (sysUser.getUserCreatorId() != null && !sysUser.getUserCreatorId().equals("")) {
                    QueryWrapper<SysUser> queryWrapper6 = new QueryWrapper<>();
                    queryWrapper6.eq("ID", sysUser.getUserCreatorId());
                    SysUser sysUser1 = iSysUserService.getOne(queryWrapper6);
                    if (sysUser1 != null) {
                        userVo.setCreateBy(sysUser1.getTrueName());
                    }
                }
                if (sysUser.getUserUpdatorId() != null && !sysUser.getUserUpdatorId().equals("")) {
                    QueryWrapper<SysUser> queryWrapper7 = new QueryWrapper<>();
                    queryWrapper7.eq("ID", sysUser.getUserUpdatorId());
                    SysUser sysUser2 = iSysUserService.getOne(queryWrapper7);
                    if (sysUser2 != null)
                        userVo.setUpdateBy(sysUser2.getTrueName());
                }
                if (sysUser.getAppAuthority1() != null && !sysUser.getAppAuthority1().equals("")) {
                    String defaultCodeApp = sysUser.getAppAuthority1();
                    char[] arr = defaultCodeApp.toCharArray();
                    List<String> list1 = new ArrayList<>();
                    for (int i = 0; i < arr.length; i++) {
                        String str = String.valueOf(arr[i]);
                        if (str.equals("1")) {//i=1
                            QueryWrapper<SysRoleInfoFunction> queryWrapper3 = new QueryWrapper<>();
                            queryWrapper3.eq("WEB_FUNCTION_NUMBER", i);
                            SysRoleInfoFunction one = iSysRoleInfoFunctionService.getOne(queryWrapper3);
                            if (one == null) {
                                continue;
                            }
                            String webFunctionExplain = one.getWebFunctionExplain();
                            list1.add(webFunctionExplain);
                        }
                        userVo.setAppNameList(list1);
                    }
                }
                if (sysUser.getAppAuthority2() != null && !sysUser.getAppAuthority2().equals("")) {
                    String defaultCodeWeb = sysUser.getAppAuthority2();
                    char[] arr1 = defaultCodeWeb.toCharArray();
                    List<String> list2 = new ArrayList<>();
                    for (int i = 0; i < arr1.length; i++) {
                        String str = String.valueOf(arr1[i]);
                        if (str.equals("1")) {//i=1
                            QueryWrapper<SysRoleInfoFunctionWeb> queryWrapper3 = new QueryWrapper<>();
                            queryWrapper3.eq("WEB_FUNCTION_NUMBER", i);
                            SysRoleInfoFunctionWeb one = iSysRoleInfoFunctionWebService.getOne(queryWrapper3);
                            if (one == null) {
                                continue;
                            }
                            String webFunctionExplain = one.getWebFunctionExplain();
                            list2.add(webFunctionExplain);
                        }
                        userVo.setWebNameList(list2);
                    }
                }
                QueryWrapper<SysUserPlantConn> queryWrapper8 = new QueryWrapper<>();
                queryWrapper8.eq("USER_ID", sysUser.getId());
                List<String> list = new ArrayList<>();
                List<String> list3 = new ArrayList<>();
                List<SysUserPlantConn> userPlantConnList = iSysUserPlantConnService.list(queryWrapper8);
                for (SysUserPlantConn sysUserPlantConn : userPlantConnList) {
                    QueryWrapper<TPlants> queryWrapper9 = new QueryWrapper<>();
                    queryWrapper9.eq("ID", sysUserPlantConn.getPlantId());
                    TPlants tPlants = iTPlantsService.getOne(queryWrapper9);
                    String plantFullName = tPlants.getPlantFullName();
                    list.add(plantFullName);
                    list3.add(tPlants.getId());
                }
                userVo.setConnectPlantList(list);
                userVo.setConnectPlantIdList(list3);
                userVos.add(userVo);
            }
            Map<String, Object> map = new HashMap<>();
            map.put("total", sysUserIPage.getTotal());
            map.put("list", userVos);
            return SzResult.success(map);
        }
    }

    //重置用户密码
    public SzResult resetUserPwd(String token, String id, String plantId) throws Exception {
        // 获取当前登录用户信息
        SysUser user = userInfoDao.getUser(StpUtil.getLoginIdByToken(token).toString());
        SysRole sysRole = userInfoDao.getUserRole(id);
        QueryWrapper<SysDic> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("DIC_TYPE", "userIniPwd");
        queryWrapper.eq("DIC_KEY", sysRole.getRoleCode().substring(0, 1));
        SysDic sysDic1 = iSysDicService.getOne(queryWrapper);
        SysUser sysUser = iSysUserService.getById(id);
        sysUser.setPwdDetail(sysDic1.getDicVal());
        sysUser.setPassword(MD5Util.getMd5(sysDic1.getDicVal()).toUpperCase());
        iSysUserService.updateById(sysUser);
        sysLogBu.logRecord("重置用户密码", user.getTrueName(), "重置了【" + sysUser.getTrueName() + "】的密码", plantId);
        Map<String, Object> map = new HashMap<>();
        map.put("pwd", sysDic1.getDicVal());
        return SzResult.success(map);
    }

    public SzResult updateAppAuthority2(Integer nubmer, String id, Integer ifOn, String token, String plantId) throws Exception {

        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ID", id);
        SysUser user = iSysUserService.getOne(queryWrapper);
        String defaultCodeWeb = user.getAppAuthority2();
//    defaultCodeWeb转成Integer数组
        Integer[] list1 = defaultCodeWeb.chars()
                .mapToObj(c -> Integer.parseInt(String.valueOf((char) c)))
                .toArray(Integer[]::new);
        list1[nubmer] = ifOn;
        String defaultCodeWeb1 = Arrays.toString(list1).replace("[", "").replace("]", "").replace(",", "").replace(" ", "");
        user.setAppAuthority2(defaultCodeWeb1);
        iSysUserService.updateById(user);
        SysUser user1 = userInfoDao.getUser(StpUtil.getLoginIdByToken(token).toString());
        QueryWrapper<SysRoleInfoFunctionWeb> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("WEB_FUNCTION_NUMBER", nubmer);
        SysRoleInfoFunctionWeb sysRoleInfoFunctionWeb = sysRoleInfoFunctionWebService.getOne(queryWrapper1);
        if (ifOn == 0) {
            sysLogBu.logRecord("修改用户web权限", user1.getTrueName(), "关闭了" + user.getTrueName() + "的" + sysRoleInfoFunctionWeb.getWebFunctionExplain() + "权限", plantId);
            return SzResult.success("关闭成功");
        } else {
            sysLogBu.logRecord("修改用户web权限", user1.getTrueName(), "开启了" + user.getTrueName() + "的" + sysRoleInfoFunctionWeb.getWebFunctionExplain() + "权限", plantId);
            return SzResult.success("开启成功");
        }
    }
    //一键重置不同角色用户权限
    public SzResult resetAllAuthority(String partId,String token, String plantId) throws Exception {
        SysPart sysPart = iSysPartService.getById(partId);
        if (sysPart == null) {
            return SzResult.error("没有该角色");
        }
        QueryWrapper<SysUserPartConn> sysUserPartConnQueryWrapper = new QueryWrapper<>();
        sysUserPartConnQueryWrapper.eq("PART_ID",partId);
        for (SysUserPartConn sysUserPartConn : iSysUserPartConnService.list(sysUserPartConnQueryWrapper)) {
            QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("ID", sysUserPartConn.getUserId());
            queryWrapper.eq("DATA_FROM", plantId);
            SysUser sysUser = iSysUserService.getOne(queryWrapper);
            if (sysUser == null) {
                log.error("没有该用户"+sysUserPartConn.getUserId());
            }else {
                sysUser.setAppAuthority1(sysPart.getDefaultCodeApp());
                sysUser.setAppAuthority2(sysPart.getDefaultCodeWeb());
                iSysUserService.updateById(sysUser);
            }
        }


        SysUser user = userInfoDao.getUser(StpUtil.getLoginIdByToken(token).toString());
        sysLogBu.logRecord("重置用户权限", user.getTrueName(), "一键重置了不同角色用户权限" + user.getTrueName() , plantId);
        return SzResult.success("重置成功");
    }
    //重置用户权限
    public SzResult resetAuthority(String id,String token, String plantId) throws Exception {
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        queryWrapper.eq("DATA_FROM", plantId);
        SysUser sysUser = iSysUserService.getOne(queryWrapper);
        if (sysUser == null) {
            return SzResult.error("用户不存在");
        }
        QueryWrapper<SysUserPartConn> sysUserPartConnQueryWrapper = new QueryWrapper<>();
        sysUserPartConnQueryWrapper.eq("USER_ID",sysUser.getId());
        SysUserPartConn sysUserPartConn = iSysUserPartConnService.getOne(sysUserPartConnQueryWrapper);
        if (sysUserPartConn == null) {
            return SzResult.error(sysUser.getUserName()+"用户未绑定角色,"+"id为："+sysUser.getId());
        }
        SysPart sysPart = iSysPartService.getById(sysUserPartConn.getPartId());
        if (sysPart == null) {
            return SzResult.error(sysUser.getUserName()+"用户角色权限不存在,"+"id为："+sysUser.getId());
        }
        sysUser.setAppAuthority1(sysPart.getDefaultCodeApp());
        if (sysPart.getDefaultCodeWeb() != null) {
            sysUser.setAppAuthority2(sysPart.getDefaultCodeWeb());
        }
        iSysUserService.updateById(sysUser);
        SysUser user = userInfoDao.getUser(StpUtil.getLoginIdByToken(token).toString());
        sysLogBu.logRecord("重置用户权限", user.getTrueName(), "重置了"+ sysUser.getUserName() +"用户权限" + user.getTrueName() , plantId);
        return SzResult.success("重置成功");
    }

    //    updateDefaultCodeApp
    public SzResult updateAppAuthority1(Integer nubmer, String id, Integer ifOn, String token, String plantId) throws Exception {
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ID", id);
        SysUser user = iSysUserService.getOne(queryWrapper);
        String defaultCodeApp = user.getAppAuthority1();
//    defaultCodeApp 转换成数组
        Integer[] list1 = defaultCodeApp.chars()
                .mapToObj(c -> Integer.parseInt(String.valueOf((char) c)))
                .toArray(Integer[]::new);
        list1[nubmer] = ifOn;
        String defaultCodeApp1 = Arrays.toString(list1).replace("[", "").replace("]", "").replace(",", "").replace(" ", "");
        user.setAppAuthority1(defaultCodeApp1);
        iSysUserService.updateById(user);
        SysUser user1 = userInfoDao.getUser(StpUtil.getLoginIdByToken(token).toString());
        QueryWrapper<SysRoleInfoFunction> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("WEB_FUNCTION_NUMBER", nubmer);
        SysRoleInfoFunction sysRoleInfoFunctionApp = sysRoleInfoFunctionService.getOne(queryWrapper1);
        if (ifOn == 0) {
            sysLogBu.logRecord("修改用户App权限", user1.getTrueName(), "关闭了" + user.getTrueName() + "的" + sysRoleInfoFunctionApp.getWebFunctionExplain() + "权限", plantId);
            return SzResult.success("关闭成功");
        } else {
            sysLogBu.logRecord("修改用户App权限", user1.getTrueName(), "开启了" + user.getTrueName() + "的" + sysRoleInfoFunctionApp.getWebFunctionExplain() + "权限", plantId);
            return SzResult.success("开启成功");
        }
    }

//    @Test
//    public void simpleFill() {
//        Path path = Paths.get("C:\\Users\\xiaoxu\\Desktop\\todo\\user.xlsx");
//        FillData fillData = new FillData();
//        fillData.setName("张三");
//        fillData.setNumber(5.1);
//        fillData.setDate(new Date());
//        EasyExcel.write("C:\\Users\\xiaoxu\\Desktop\\todo\\user_output1.xlsx", FillData.class)
//                .withTemplate(path.toString())
//                .sheet()
//                .doFill(fillData);
//    }


    public Future<List<PersonalExcelEn>> userExportExcel(List<Map<String, Object>> fields, String filename, List<Map<String, Object>> ids, boolean isHeader, String mode, Boolean original, Map<String, String> pager, String sheetName, String plantId, String trueName, String phone) {
        List<Map<String, Object>> newIds = new ArrayList<>();
//        最终数据
        List<PersonalExcelEn> list = new ArrayList<>();
        try {
            switch (mode) {
                case "current":
                    for (Map<String, Object> id : ids) {
                        Map<String, Object> newId = new HashMap<>();
                        for (Map<String, Object> field : fields) {
                            if (id.containsKey(field.get("field"))) {
                                newId.put(field.get("field").toString(), id.get(field.get("field")));
                            }
                        }
                        newIds.add(newId);
                    }
//             newIds为Map<String, Object>类型,需要转换为NoticeExcelEn类型
                    for (Map<String, Object> newId : newIds) {
                        PersonalExcelEn personalExcelEn = PersonalExcelEn.builder().build();

                        for (Map.Entry<String, Object> entry : newId.entrySet()) {

                            if (entry.getKey().equals("userName")) {
                                if (entry.getValue() != null) {
                                    personalExcelEn.setUserName(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("trueName")) {
                                if (entry.getValue() != null) {
                                    personalExcelEn.setTrueName(entry.getValue().toString());
                                }
                            }
//                           trucksTrailerno
                            if (entry.getKey().equals("phone")) {
                                if (entry.getValue() != null) {
                                    personalExcelEn.setPhone(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("idCard")) {
                                if (entry.getValue() != null) {
                                    personalExcelEn.setIdCard(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("partName")) {
                                if (entry.getValue() != null) {
                                    personalExcelEn.setPartName(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("roleName")) {
                                if (entry.getValue() != null) {
                                    personalExcelEn.setRoleName(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("orgName")) {
                                if (entry.getValue() != null) {
                                    personalExcelEn.setOrgName(entry.getValue().toString());
                                }
                            }
//                           trucksTrailerno
                            if (entry.getKey().equals("roleLevel")) {
                                if (entry.getValue() != null) {
                                    personalExcelEn.setRoleLevel(entry.getValue().toString());
                                }
                            }


                            if (entry.getKey().equals("createTime")) {
                                if (entry.getValue() != null) {
                                    personalExcelEn.setCreateTime(entry.getValue().toString());
                                }
                            }
//                           trucksTrailerno
                            if (entry.getKey().equals("createBy")) {
                                if (entry.getValue() != null) {
                                    personalExcelEn.setCreateBy(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("updateTime")) {
                                if (entry.getValue() != null) {
                                    personalExcelEn.setUpdateTime(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("updateBy")) {
                                if (entry.getValue() != null) {
                                    personalExcelEn.setUpdateBy(entry.getValue().toString());
                                }
                            }
//                           trucksTrailerno
                            if (entry.getKey().equals("ifApp")) {
                                if (entry.getValue() != null) {
                                    personalExcelEn.setIfApp(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("ifWeb")) {
                                if (entry.getValue() != null) {
                                    personalExcelEn.setIfWeb(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("appNameList")) {
                                if (entry.getValue() != null) {
                                    personalExcelEn.setAppNameList(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("webNameList")) {
                                if (entry.getValue() != null) {
                                    personalExcelEn.setWebNameList(entry.getValue().toString());
                                }
                            }
                        }
                        list.add(personalExcelEn);
                    }
                    break;
                case "all":
                    QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
                    queryWrapper.like(trueName != null && !trueName.equals(""), "TRUE_NAME", trueName);
                    queryWrapper.like(phone != null && !phone.equals(""), "PHONE", phone);
                    queryWrapper.eq("DEL_FLAG", 0);
                    queryWrapper.eq("DATA_FROM", plantId);
                    List<SysUser> sysUsers = iSysUserService.list(queryWrapper);
                    for (SysUser sysUser : sysUsers) {
                        PersonalExcelEn personalExcelEn = PersonalExcelEn.builder()
                                .userName(Optional.ofNullable(sysUser.getUserName()).orElse(""))
                                .trueName(Optional.ofNullable(sysUser.getTrueName()).orElse(""))
                                .phone(Optional.ofNullable(sysUser.getPhone()).map(Object::toString).orElse(""))
                                .email(Optional.ofNullable(sysUser.getEmail()).map(Object::toString).orElse(""))
                                .idCard(Optional.ofNullable(sysUser.getIdCard()).map(Object::toString).orElse(""))
                                .partName(Optional.ofNullable(userDic.getPartDic(sysUser.getId())).orElse(""))
                                .roleName(Optional.ofNullable(userDic.getRoleDic(sysUser.getId())).orElse(""))
                                .orgName(Optional.ofNullable(userDic.getOrgDic(sysUser.getId())).orElse(""))
                                .roleLevel(Optional.ofNullable(userDic.getRoleDic(sysUser.getId())).orElse(""))
                                .createTime(Optional.ofNullable(sysUser.getUserCreatTime()).map(Object::toString).orElse(""))
                                .createBy(Optional.ofNullable(sysUser.getTrueName()).map(Object::toString).orElse(""))
                                .updateTime(Optional.ofNullable(sysUser.getUserUpdateTime()).map(Object::toString).orElse(""))
                                .updateBy(Optional.ofNullable(sysUser.getTrueName()).orElse(""))
                                .ifApp(Optional.ofNullable(sysUser.getIfApp()).map(Object::toString).orElse(""))
                                .ifWeb(Optional.ofNullable(sysUser.getIfWeb()).map(Object::toString).orElse(""))
                                .appNameList(Optional.ofNullable(userDic.getAppNameListDic(sysUser.getId())).orElse(""))
                                .webNameList(Optional.ofNullable(userDic.getWebNameListDic(sysUser.getId())).orElse(""))
                                .build();
                        list.add(personalExcelEn);
                    }
                    break;
                case "selected":
                    for (Map<String, Object> id : ids) {
                        Map<String, Object> newId = new HashMap<>();
                        for (Map<String, Object> field : fields) {
                            if (id.containsKey(field.get("field"))) {
                                newId.put(field.get("field").toString(), id.get(field.get("field")));
                            }
                        }
                        newIds.add(newId);
                    }
//             newIds为Map<String, Object>类型,需要转换为NoticeExcelEn类型
                    for (Map<String, Object> newId : newIds) {
                        PersonalExcelEn personalExcelEn = PersonalExcelEn.builder().build();
                        for (Map.Entry<String, Object> entry : newId.entrySet()) {

                            if (entry.getKey().equals("userName")) {
                                if (entry.getValue() != null) {
                                    personalExcelEn.setUserName(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("trueName")) {
                                if (entry.getValue() != null) {
                                    personalExcelEn.setTrueName(entry.getValue().toString());
                                }
                            }
//                           trucksTrailerno
                            if (entry.getKey().equals("phone")) {
                                if (entry.getValue() != null) {
                                    personalExcelEn.setPhone(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("idCard")) {
                                if (entry.getValue() != null) {
                                    personalExcelEn.setIdCard(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("partName")) {
                                if (entry.getValue() != null) {
                                    personalExcelEn.setPartName(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("roleName")) {
                                if (entry.getValue() != null) {
                                    personalExcelEn.setRoleName(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("orgName")) {
                                if (entry.getValue() != null) {
                                    personalExcelEn.setOrgName(entry.getValue().toString());
                                }
                            }
//                           trucksTrailerno
                            if (entry.getKey().equals("roleLevel")) {
                                if (entry.getValue() != null) {
                                    personalExcelEn.setRoleLevel(entry.getValue().toString());
                                }
                            }


                            if (entry.getKey().equals("createTime")) {
                                if (entry.getValue() != null) {
                                    personalExcelEn.setCreateTime(entry.getValue().toString());
                                }
                            }
//                           trucksTrailerno
                            if (entry.getKey().equals("createBy")) {
                                if (entry.getValue() != null) {
                                    personalExcelEn.setCreateBy(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("updateTime")) {
                                if (entry.getValue() != null) {
                                    personalExcelEn.setUpdateTime(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("updateBy")) {
                                if (entry.getValue() != null) {
                                    personalExcelEn.setUpdateBy(entry.getValue().toString());
                                }
                            }
//                           trucksTrailerno
                            if (entry.getKey().equals("ifApp")) {
                                if (entry.getValue() != null) {
                                    personalExcelEn.setIfApp(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("ifWeb")) {
                                if (entry.getValue() != null) {
                                    personalExcelEn.setIfWeb(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("appNameList")) {
                                if (entry.getValue() != null) {
                                    personalExcelEn.setAppNameList(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("webNameList")) {
                                if (entry.getValue() != null) {
                                    personalExcelEn.setWebNameList(entry.getValue().toString());
                                }
                            }
                        }
                        list.add(personalExcelEn);
                    }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new AsyncResult<>(list);
    }


    /**
     * 获取司机用户信息
     */
    public SzResult getDriver(String driver,String plantId) {
        QueryWrapper<SysUserRoleConn> SysUserRoleConnQueryWrapper = new QueryWrapper<>();
        SysUserRoleConnQueryWrapper.eq("ROLE_ID", "cb83f83bb9f1fc740ae3d5be1d3e4fe9");

        List<SysUserRoleConn> sysUserRoleConns = iSysUserRoleConnService.list(SysUserRoleConnQueryWrapper);
        List<String> userIds = new ArrayList<>();
        for (SysUserRoleConn sysUserRoleConn : sysUserRoleConns) {
            userIds.add(sysUserRoleConn.getUserId());
        }
        QueryWrapper<SysUser> sysUserQueryWrapper = new QueryWrapper<>();
        if (userIds.isEmpty()) {
            // 当userIds列表为空时，返回相应的结果或抛出异常
            return SzResult.Error("暂无司机用户");
        } else {
            sysUserQueryWrapper.in("ID", userIds);
            sysUserQueryWrapper.ne("DEL_FLAG", 1);
            sysUserQueryWrapper.eq("DATA_FROM",plantId);
            sysUserQueryWrapper.like(driver != null && !driver.equals(""), "TRUE_NAME", driver);
            sysUserQueryWrapper.select(SysUser.class, info -> !info.getColumn().equals("password") && !info.getColumn().equals("pwd_detail"));
            List<SysUser> sysUsers = iSysUserService.list(sysUserQueryWrapper);
            return SzResult.success(sysUsers);
        }

    }


    /**
     * 冻结用户
     */
    public SzResult frozenUser(String id, String token, String plantId) throws Exception {
        SysUser user = userInfoDao.getUser(StpUtil.getLoginIdByToken(token).toString());
        SysUser sysUser = iSysUserService.getById(id);
        sysUser.setEnableFlag(0);
        iSysUserService.updateById(sysUser);
        sysLogBu.logRecord("冻结用户", user.getTrueName(), "冻结了【" + sysUser.getTrueName() + "】", plantId);
        return SzResult.success("冻结成功");
    }

    /**
     * 解冻
     */
    public SzResult unfrozenUser(String id, String token, String plantId) throws Exception {
        SysUser user = userInfoDao.getUser(StpUtil.getLoginIdByToken(token).toString());
        SysUser sysUser = iSysUserService.getById(id);
        sysUser.setEnableFlag(1);
        iSysUserService.updateById(sysUser);
        sysLogBu.logRecord("解冻用户", user.getTrueName(), "解冻了【" + sysUser.getTrueName() + "】", plantId);
        return SzResult.success("解冻成功");
    }

    /**
     * 修改用户关联厂
     */
    public SzResult updateUserConnectPlant(String userId, List<String> plantIdList, String token, String plantId) throws Exception {
        String trueName = userInfoDao.getUser(StpUtil.getLoginIdByToken(token).toString()).getTrueName();
        QueryWrapper<SysUserPlantConn> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("USER_ID", userId);
        List<SysUserPlantConn> userPlantConnList = iSysUserPlantConnService.list(queryWrapper1);
        if (plantIdList == null) {
            return SzResult.error("请选择关联厂");
        }
        if (!plantIdList.isEmpty()) {
            iSysUserPlantConnService.remove(queryWrapper1);
        }
        for (String updatePlantId : plantIdList) {
            SysUserPlantConn sysUserPlantConn = new SysUserPlantConn();
            sysUserPlantConn.setUserId(userId);
            sysUserPlantConn.setPlantId(updatePlantId);
            iSysUserPlantConnService.save(sysUserPlantConn);
        }
        List<String> list = new ArrayList<>();
        for (SysUserPlantConn sysUserPlantConn : userPlantConnList) {
            String plantId1 = sysUserPlantConn.getPlantId();
            QueryWrapper<TPlants> queryWrapper2 = new QueryWrapper<>();
            queryWrapper2.eq("ID", plantId1);
            TPlants tPlants = iTPlantsService.getOne(queryWrapper2);
            list.add(tPlants.getPlantFullName());
        }
        List<String> list1 = new ArrayList<>();
        for (String plantId1 : plantIdList) {
            QueryWrapper<TPlants> queryWrapper2 = new QueryWrapper<>();
            queryWrapper2.eq("ID", plantId1);
            TPlants tPlants = iTPlantsService.getOne(queryWrapper2);
            list1.add(tPlants.getPlantFullName());
        }
        sysLogBu.logRecord("修改用户关联厂", trueName, "将用户关联的厂由【" + list + "】修改为【" + list1 + "】", plantId);
        return SzResult.Success();
    }
//绑定用户微信id
    public SzResult updateUserWxConn(String id, String wxOpenId, String token) {
        SysUserWxConn sysUserWxConn = new SysUserWxConn();
        sysUserWxConn.setUserId(id);
        sysUserWxConn.setWxOpenId(wxOpenId);
        QueryWrapper<SysUserWxConn> wxConnQueryWrapper = new QueryWrapper<>();
        wxConnQueryWrapper.eq("USER_ID",id);
        SysUserWxConn one = iSysUserWxConnService.getOne(wxConnQueryWrapper);
        if (one == null) {
            iSysUserWxConnService.save(sysUserWxConn);
            return  SzResult.success("新增成功");
        }else {
            sysUserWxConn.setId(one.getId());
            iSysUserWxConnService.updateById(sysUserWxConn);
            return  SzResult.success("修改成功");
        }
    }
}